package com.scu.bank.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scu.bank.model.dao.UserInfoDao;
import com.scu.bank.model.example.UserInfoExample;
import com.scu.bank.model.pojo.UserInfo;
import com.scu.bank.model.base.BaseServiceImpl;
import com.scu.bank.model.pojo.UserRole;
import com.scu.bank.service.UserInfoService;
import com.scu.bank.service.UserRoleService;
import com.scu.bank.util.VerificationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;

/**
 * Created by pmeng on 2020/05/26.
 */
@Service
@Transactional
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfo,UserInfoDao> implements UserInfoService {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserInfoDao getDao() {
        return userInfoDao;
    }

    @Override
    public PageInfo<UserInfo> list(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        UserInfoExample example = new UserInfoExample();
        example.createCriteria().andIsDelEqualTo(false);
        PageInfo<UserInfo> pageInfo = new PageInfo(userInfoDao.selectByExample(example));

        for (UserInfo userInfo : pageInfo.getList()){
            UserRole userRole = userRoleService.getById(userInfo.getUserRole());
            userInfo.setUserRoleName(userRole == null ? "无" : userRole.getName());
            userInfo.setCipher(null);
        }

        return pageInfo;
    }

    @Override
    public void addUserInfo(UserInfo userInfo) {
        userInfo.setUserStatus("0");
        userInfo.setUserRole("1");
        userInfo.setIsAdmin(false);
        String pwd=DigestUtils.md5DigestAsHex("123456".getBytes());
        userInfo.setCipher(pwd);
        save(userInfo);
    }

    @Override
    public void restPwd(String id, String pwd) {
        UserInfo userInfo = getById(id);
        VerificationUtil.checkServiceBusiness(userInfo == null,"参数异常!");

        String pwdMD5=DigestUtils.md5DigestAsHex(pwd.getBytes());
        userInfo.setCipher(pwdMD5);
        update(userInfo);
    }

    @Override
    public void setRole(String uId, String roleId) {
        UserInfo userInfo = getById(uId);
        VerificationUtil.checkServiceBusiness(userInfo == null,"数据不存在!");
        UserRole userRole = userRoleService.getById(roleId);
        VerificationUtil.checkServiceBusiness(userRole == null,"角色不存在!");

        userInfo.setUserRole(roleId);
        update(userInfo);
    }

}
